package com.example.uniapp.dao;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.uniapp.bean.UserBean;
import com.example.uniapp.db.DBUtils;

import java.util.List;

/**
 * 操作用户数据库
 */
public class UserDao {

    private static final SQLiteDatabase db = DBUtils.con;

    /**
     * 保存用户数据到数据库
     * @param account
     * @param pwd
     * @param avator
     * @return
     */
    public static int saveUser(String account, String pwd, String avator) {
        String[] data = {account, pwd, avator};
        //向数据库加入数据
        try {
            db.execSQL("INSERT INTO users (user_id, user_pwd, user_avator)" +
                            "VALUES (?, ?, ?)",
                    data);
            return 1;
        }catch (Exception e) {
            return 0;
        }
    }

    /**
     * 登录功能
     * @param account
     * @param pwd
     * @return
     */
    public static int login(String account, String pwd) {
        String[] data = {account, pwd};
        String sql = "select * from users where user_id=? and user_pwd=?";
        Cursor result = db.rawQuery(sql, data);
        while(result.moveToNext()) {
            return 1;
        }
        return 0;
    }

    /**
     * 通过用户名查找用户信息
     * @param account
     * @return
     */
    @SuppressLint("Range")
    public static UserBean getUserInfoByAccount(String account) {
        UserBean userBean = new UserBean();
        String sql = "select * from users where user_id=?";
        Cursor cursor = db.rawQuery(sql, new String[] {account});
        while(cursor.moveToNext()) {
            userBean.setUserId(cursor.getString(cursor.getColumnIndex("user_id")));
            userBean.setUserPwd(cursor.getString(cursor.getColumnIndex("user_pwd")));
            userBean.setUserImg(cursor.getString(cursor.getColumnIndex("user_avator")));
        }
        return userBean;
    }

    /**
     * 更新用户名和用户头像
     * @param oldUserId
     * @param newUserId
     * @param newUserImg
     * @return
     */
    public static int updateUserInfo(String oldUserId, String newUserId, String newUserImg) {
        String sql = "update users set user_id=?, user_avator=? where user_id=?";
        try {
            db.execSQL(sql, new String[] {newUserId, newUserImg, oldUserId});
            return 1;
        }catch (Exception e) {
            return 0;
        }
    }

    /**
     * 更新用户密码
     * @param userId
     * @param newPwd
     * @return
     */
    public static int updateUserPwd(String userId, String newPwd) {
        String sql = "update users set user_pwd=? where user_id=?";
        try {
            db.execSQL(sql, new String[] {newPwd, userId});
            return 1;
        }catch (Exception e) {
            return 0;
        }
    }
}
